import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { isRelogin } from '@/utils/request'

NProgress.configure({ showSpinner: false })

// 增加三方登陆 update by 芋艿
const whiteList = [
  '/login',
  '/adminLogin',
  '/social-login',
  '/auth-redirect',
  '/bind',
  '/register',
  '/oauthLogin/gitee'
]

router.beforeEach((to, from, next) => {
  NProgress.start()
  const loginType = localStorage.getItem('loginType') || 'company'
  if (getToken()) {
    to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
    /* has token*/
    if (to.path === '/login' || to.path === '/adminLogin') {
      if (loginType === 'company') {
        next({ path: '/userManage/personalCenter/checkId' })
      } else {
        next({ path: '/index/index' })
      }
    } else {
      if (store.getters.roles.length === 0) {
        isRelogin.show = true
        // 获取字典数据 add by 芋艿
        store.dispatch('dict/loadDictDatas')
        // 判断当前用户是否已拉取完user_info信息
        store
          .dispatch('GetInfo')
          .then(() => {
            isRelogin.show = false
            store.dispatch('GenerateRoutes').then((accessRoutes) => {
              // 根据roles权限生成可访问的路由表
              router.addRoutes(accessRoutes) // 动态添加可访问路由表
              if (loginType === 'company') {
                // 企业
                const isHasCheckIdRoute = accessRoutes.some(e => {
                  return e.path === '/userManage' && e.children.some(ee => {
                    return ee.path === 'personalCenter' && ee.children.some(eee => {
                      return eee.path === 'checkId'
                    })
                  })
                })
                if (store.getters.roles.indexOf('tenant_admin') > -1 || store.getters.roles.indexOf('gust') > -1) {
                  /**
                   * 企业管理员、游客，默认跳转到企业认证页面
                   * 其中企业管理员跳到【企业认证】页后，会判断认证情况，如果已认证，将跳到统计看板-----废弃
                   * 直接判断是否存在企业认证菜单，有则跳，若没有，则跳统计看板
                   */
                  if (isHasCheckIdRoute) {
                    next({
                      path: '/userManage/personalCenter/checkId',
                      replace: true
                    })
                  } else {
                    next({
                      path: '/analytics/analytics',
                      replace: true
                    })
                  }
                } else {
                  // 企业子账号（默认已认证），默认跳转到统计看板
                  next({
                    path: '/analytics/analytics',
                    replace: true
                  })
                }
              } else {
                // 运营,跳到统计看板
                next({ path: '/index/index', replace: true })
              }
              // next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
            })
          })
          .catch((err) => {
            store.dispatch('LogOut').then(() => {
              Message.error(err)
              if (loginType === 'company') {
                next({ path: '/login' })
              } else {
                next({ path: '/adminLogin' })
              }
            })
          })
      } else {
        next()
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      const loginType = localStorage.getItem('loginType') || 'company'
      if (loginType === 'company') {
        next({ path: '/login' }) // 否则全部重定向到登录页
      } else {
        next({ path: '/adminLogin' }) // 否则全部重定向到登录页
      }
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
